package com.jumper.property.comparer.starter;

import com.jumper.property.comparer.starter.constant.LogStarterConstant;
import com.jumper.property.comparer.starter.mybatis.BusOptLogMapper;
import com.jumper.property.comparer.starter.mybatis.MybatisLogRepositoryImpl;
import com.jumper.property.comparer.core.support.LogRepository;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;

@Slf4j
public class MybatisBusLogAutoConfiguration implements ApplicationContextAware {

    /**
     * Spring容器
     */
    private ApplicationContext ctx;

    /**
     * 当orm为mybatis时扫描自定义Mapper
     */
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage(LogStarterConstant.MYBATIS_SCAN_PACKAGE);
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return configurer;
    }

    /**
     * 注入业务日志仓库
     */
    @Bean
    public LogRepository busOptLogRepository() {
        return getMybatisRepository();
    }

    /**
     * Mybatis实现
     */
    private LogRepository getMybatisRepository() {
        BusOptLogMapper mapper = ctx.getBean(BusOptLogMapper.class);
        return new MybatisLogRepositoryImpl(mapper);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
